package cn.com.fssg.platform.base.handler.impl.gsl.common;

import cn.com.fssg.platform.base.handler.InterfaceHandler;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Description: 工商联届次信息插入数据接口
 */
@Component
public class GslEncryptCtl implements InterfaceHandler {

    public static final String ALGORITHM = "AES";

    // 密钥补全
    public static byte[] padKey(byte[] key, int length) {
        return Arrays.copyOf(key, length);
    }

    /**
     * HEX 字符串转字节数组
     */
    public static byte[] hexToBytes(String hex) {
        byte[] bytes = new byte[hex.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
        }
        return bytes;
    }

    /**
     * 字节数组转HEX字符串（替代Base64）
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuilder hex = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) {
            hex.append(String.format("%02X", b));
        }
        return hex.toString();
    }

    /** 加密 */
    public static String encrypt(String input, String keys) throws Exception {
        // 1. 补全密钥为16字节（AES-128）
        byte[] keyBytes = padKey(keys.getBytes(StandardCharsets.UTF_8), 16);
        SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");

        // 2. 初始化加密器
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);

        // 3. 加密并转为HEX字符串
        byte[] encryptedBytes = cipher.doFinal(input.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(encryptedBytes);
    }

    /** 解密 */
    public static String decrypt(String input, String keys) throws Exception {
        // 1. HEX 字符串 → 字节数组
        byte[] cipherBytes = hexToBytes(input);
        byte[] keyBytes = padKey(keys.getBytes(StandardCharsets.UTF_8), 16);
        SecretKeySpec key = new SecretKeySpec(keyBytes, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decrypted = cipher.doFinal(cipherBytes);
        return new String(decrypted, StandardCharsets.UTF_8);
    }

    @Override
    public Object run(HttpServletRequest request, JSONObject jsonObject) throws Exception {
        String text = jsonObject.getString("content");
        try {
            String key = jsonObject.getString("key");
            return decrypt(text, key);
        } catch (Exception e) {
            return text;
        }
    }
}
